package master.common.json;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.util.Date;

/**
 * 用来统一返回 JSON对象
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
public class JSONResponseObject implements JSONAware {

    private boolean success;

    private Object value; //TODO: List Map

    private String errorMsg;

    private Exception exception;

    private JSONResponseObject(boolean success) {
        this.success = success;
    }

    public static JSONResponseObject newSuccessJSONResponseObject(){
        return new JSONResponseObject(true);
    }

    public static JSONResponseObject newFailureJSONResponseObject(){
        return new JSONResponseObject(false);
    }

    public boolean isSuccess() {
        return success;
    }

    public JSONResponseObject setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public Object getValue() {
        return value;
    }

    public JSONResponseObject setValue(Object value) {
        this.value = value;
        return this;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public JSONResponseObject setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
        return this;
    }

    public Exception getException() {
        return exception;
    }

    public JSONResponseObject setException(Exception exception) {
        this.exception = exception;
        return this;
    }

    public String toJSONString() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("success", isSuccess());
        if(isSuccess()) {
            jsonObject.put("value", JSONValue.toJSONString(getValue()));
        }
        else {
            jsonObject.put("errorMsg", getErrorMsg());
            jsonObject.put("exception", getException());
        }
        
        jsonObject.put("responseTime", new Date().toString());
        return jsonObject.toJSONString();
    }

    @Override
    public String toString() {
        return toJSONString();
    }
}
